package com.softcits.sb01.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.fasterxml.jackson.core.type.TypeReference;

@WebServlet(urlPatterns="/weather")
public class WeatherServlet extends HttpServlet {
    private String weatherUrl = "http://api.apixu.com/v1/current.json?key=b8ff99e79c9340d79fa161843190703&q=";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        
        String cityCode = req.getParameter("city");
        if(null == cityCode || "".equals(cityCode)) {
            resp.getWriter().write("Please specify the parameter City Code.");
            return;
        }
        URL url = new URL(weatherUrl + cityCode);
        InputStream is = url.openStream();
        InputStreamReader isr = new InputStreamReader(is);
        char[] cArr = new char[2048];
        int data = -1;
        StringBuilder buf = new StringBuilder();
        while((data = isr.read(cArr, 0, cArr.length)) != -1) {
            buf.append(cArr, 0, data);
        }

        JSONObject jobj = JSONObject.parseObject(buf.toString());
        JSONObject current = jobj.getObject("current", JSONObject.class);
        String weather = current.getString("temp_c");
        String updateTime = current.getString("last_updated");
        String wind = current.getString("wind_mph");
        JSONObject condition = current.getObject("condition", JSONObject.class);
        String text = condition.getString("text");
        JSONObject location = jobj.getObject("location", JSONObject.class);
        String cityName = location.getString("name");
        JSONObject targetObject = new JSONObject();
        targetObject.put("city", cityName);
        targetObject.put("temp_c", weather);
        targetObject.put("last_updated", updateTime);
        targetObject.put("wind_mph", wind);
        targetObject.put("text", text);
        String targetJson = JSONObject.toJSONString(targetObject);
        
        resp.getWriter().write(targetJson);
        
    }
}
